package client.service;

import common.Message;
import common.MessageStatus;


import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Arrays;

public class UserThread extends Thread{
    private Socket socket;


    public UserThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        while(true){
            try {
                System.out.println("\n等待服务端发送消息");
                ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
                Message message =(Message) objIn.readObject();


                if(message.getType()== MessageStatus.RETURN_ONLINE_FRIEND){
                    String[] content = message.getContent().split(" ");
                    System.out.println("\n当前在线好友如下:");
                    System.out.println(Arrays.toString(content));
                }else if(message.getType()== MessageStatus.NORMAL_EXIT_SUCCEED){
                    break;
                }else if(message.getType()==MessageStatus.PRIVATE_CHAT){
                    System.out.println(message);
                }else if(message.getType()==MessageStatus.GROUP_CHAT){
                    System.out.println(message);
                }else if(message.getType()==MessageStatus.PRIVATE_SEND_FILE){

                    System.out.println("\n"+message.getSend_time()+" to"+message.getGetter()+" "+message.getType()+"\n"+
                            message.getSender()+": 发送 "+message.getFileName()
                    );

                    FileOutputStream fileOut = new FileOutputStream(ChatService.storeFolder+"\\"+message.getFileName());
                    fileOut.write(message.getFileBytes());
                    fileOut.flush();
                    fileOut.close();
                }
                else{
                    System.out.println("\n其他");
                }


            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage()+" ==============================================================================");
            }
        }
    }

    public Socket getSocket() {
        return socket;
    }
}
